/******************************************************************************* 
 * Copyright (C) 2012-2015 Microfountain Technology, Inc. All Rights Reserved. 
 * 
 * Unauthorized copying of this file, via any medium is strictly prohibited.   
 * Proprietary and confidential
 * 
 * Last Modified: 2015-9-17 19:33:20
 ******************************************************************************/
package cn.com.xy.sms.sdk.db;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.LineNumberReader;
import java.util.Hashtable;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.entity.CenterNumLocationInfo;
import cn.com.xy.sms.sdk.db.entity.CountSceneManager;
import cn.com.xy.sms.sdk.db.entity.EmergencyManger;
import cn.com.xy.sms.sdk.db.entity.IccidInfoManager;
import cn.com.xy.sms.sdk.db.entity.JarSubInfoManager;
import cn.com.xy.sms.sdk.db.entity.MatchCacheManager;
import cn.com.xy.sms.sdk.db.entity.MsgUrlManager;
import cn.com.xy.sms.sdk.db.entity.NetQueryTimeManager;
import cn.com.xy.sms.sdk.db.entity.OperatorCmdManager;
import cn.com.xy.sms.sdk.db.entity.OperatorParseManager;
import cn.com.xy.sms.sdk.db.entity.PhoneNumServeManager;
import cn.com.xy.sms.sdk.db.entity.PhoneSmsParseManager;
import cn.com.xy.sms.sdk.db.entity.PopupActionManager;
import cn.com.xy.sms.sdk.db.entity.RecordActionManager;
import cn.com.xy.sms.sdk.db.entity.ResdownloadManager;
import cn.com.xy.sms.sdk.db.entity.ResourseManager;
import cn.com.xy.sms.sdk.db.entity.SceneRuleManager;
import cn.com.xy.sms.sdk.db.entity.SceneconfigManager;
import cn.com.xy.sms.sdk.db.entity.SmsParseRecorder;
import cn.com.xy.sms.sdk.db.entity.SysParamEntityManager;
import cn.com.xy.sms.sdk.db.entity.UpdateTaskManager;
import cn.com.xy.sms.sdk.db.entity.MovieMessageManager;
import cn.com.xy.sms.sdk.db.entity.UrlPreviewManager;
import cn.com.xy.sms.sdk.db.entity.XmlResdownloadManager;
import cn.com.xy.sms.sdk.db.entity.menuActionManager;
import cn.com.xy.sms.sdk.db.entity.pubinfo.CountSignInfoManager;
import cn.com.xy.sms.sdk.db.entity.pubinfo.NumNameManager;
import cn.com.xy.sms.sdk.db.entity.pubinfo.PubInfoManager;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.util.FileUtils;
import cn.com.xy.sms.sdk.util.StringUtils;
    /* SDK-421 huangzhiqiang 20160525 start */
import cn.com.xy.sms.sdk.db.entity.pubinfo.ShardDataManager;
    /* SDK-421 huangzhiqiang 20160525 end */
import cn.com.xy.sms.sdk.dex.DexUtil;
/*SDK-645 hewengao 20161019 start*/
import cn.com.xy.sms.sdk.db.entity.JarSignManager;
/*SDK-645 hewengao 20161019 end*/
public class DBManager {

    public static final String dataBaseName = "smssdk.db";
    //SDK-383 特征值识别  xusongzhou 20160414 start
    /* SDK-421 huangzhiqiang 20160525 start */
    /* SDK-459/yangzhi/2016.05.26---start--- */
    /* SDK-397 huangzhiqiang 20160524 start */
    /* SDK-500 huangzhiqiang 20160621 start */
    /* SDK-478 huangzhiqiang 20160628 start */
    /* SDK-529 huangzhiqiang 20160711 start */
    /*MEIZU-1142 zhaojiangwei 20160908 start*/
    /* SDK-631 huangzhiqiang 20161008 start */
    /* SDK-632 hewengao 20161010 start*/
    /* SDK-645 hewengao 20161019 end*/
    /* SDK-654 hewengao 20161026 start*/
    /* SDK-681 zhaojiangwei 20161117 start*/
    /* SDK-704 zhaojiangwei 20161217 start*/
    /* RM-1351 huangzhiqiang 20170407 start */
    static final int dataBaseVersion = 50;
    /* RM-1351 huangzhiqiang 20170407 end */
    /* SDK-704 zhaojiangwei 20161217 end*/
    /* SDK-681 zhaojiangwei 20161117 end*/
    /* SDK-654 hewengao 20161026 end*/
    /* SDK-645 hewengao 20161019 end*/
    /* SDK-632 hewengao 20161010 end*/
    /* SDK-631 huangzhiqiang 20161008 end */
    /*MEIZU-1142 zhaojiangwei 20160908 end*/
    /* SDK-529 huangzhiqiang 20160711 end */
    /* SDK-478 huangzhiqiang 20160628 end */
    /* SDK-500 huangzhiqiang 20160621 end */
    /* SDK-397 huangzhiqiang 20160524 end */
    /* SDK-459/yangzhi/2016.05.26---end--- */
    /* SDK-421 huangzhiqiang 20160525 end */
    //SDK-383 特征值识别  xusongzhou 20160414 end
    static MyDbHelper dbHelper = null;
    static int timeOut = 1000;
    static int sleepTime = 100;
    public static Object dblock = new Object();
    static Hashtable<SQLiteDatabase, Integer> listDB = new Hashtable<SQLiteDatabase, Integer>();

    private static SQLiteDatabase createSQLiteDatabase(Context contexts) {

        synchronized (listDB) {
            if (listDB.size() >= 10) {
                return null;
            }
            if (contexts == null) {
                LogManager.e("xiaoyuan",
                        "createSQLiteDatabase: contexts is null");
                return null;
            }
            MyDbHelper helper = getHelper(contexts);
            SQLiteDatabase db = helper.getReadableDatabase();
            Integer cnt = null;
            if (db != null) {
                cnt = listDB.get(db);
                if (cnt == null) {
                    cnt = 1;
                } else {
                    cnt++;
                }
                listDB.put(db, cnt);
                if (!db.isOpen()) {
                    // LogManager.e("duoqu_dbopen", "is not open.");
                    listDB.remove(db);
                    return null;
                }
            }
            return db;
        }
    }
    /*SDK-630 hewengao/20161002 start*/
    public synchronized static void close(SQLiteDatabase db) {
    /*SDK-630 hewengao/20161002 end*/
        try {
            if (db == null) {
                LogManager.d("duoqu_dbclose", "^^^^^^^^ db close db is null");
                return;
            }
            synchronized (listDB) {
                if (!db.isOpen()) {
                    listDB.remove(db);
                    LogManager.d("duoqu_dbclose", "$$$$$ db close is not open");
                } else {
                    Integer cnt = listDB.get(db);

                    // LogManager.d("duoqu_dbclose", "$$$$$ db close : "+cnt);
                    if (cnt == null) {
                        LogManager.d("duoqu_dbclose","$$$$$ db close cnt is null ");
                        // 这种情况如果发生就是有问题的
                        // db.close();
                    } else {
                        cnt = cnt - 1;
                        if (cnt == 0) {
                            listDB.remove(db);
                            db.close();
                            // LogManager.e("duoqu_dbclose",
                            // "$$$$$ db close : "+cnt);
                        } else {
                            listDB.put(db, cnt);
                        }
                    }
                }
            }
            if (listDB.size() == 0) {
                // LogManager.d("duoqu_dbclose", "%%%%%%%%%% listDB size is 0");
                if (dbHelper != null) {
                    // dbHelper.close();
                }
                // System.gc();
            }
        } catch (Throwable e) {
            LogManager
                    .e("xiaoyuan", "DBManager close error: " + e.getMessage());
            /* SDK-584 zhaojiangwei 20160906 start */
            DexUtil.saveExceptionLog(e);
            /* SDK-584 zhaojiangwei 20160906 end */
        }

    }

    // /**
    // * 获取开启事物的db
    // * @param beginTransaction true 开启 false:不开启
    // * @return
    // */
    // public synchronized static SQLiteDatabase getSQLDBTransaction(boolean
    // beginTransaction){
    // SQLiteDatabase db = DBManager.getSQLiteDatabase();
    // if(db != null && beginTransaction){
    // db.beginTransaction();
    // }
    // return db;
    // }
    /*SDK-630 hewengao/20161002 start*/
    public synchronized static SQLiteDatabase getSQLiteDatabase() {
    /*SDK-630 hewengao/20161002 end*/
        SQLiteDatabase sb = null;
        long start = System.currentTimeMillis();
        long end = 0;
        while (sb == null) {

            sb = createSQLiteDatabase(Constant.getContext());
            if (sb != null) {
                if (sb.inTransaction()) {
                    LogManager.d("xiaoyuan_test","getSQLiteDatabase inTransaction hashcode: ");
                }
                return sb;
            }
            end = System.currentTimeMillis();
            end = (end - start);
            if (end >= timeOut) {
                break;
            }
            try {
                Thread.sleep(sleepTime);

            } catch (InterruptedException e) {
                /*SDK-550 hewengao 20160719 start*/
                LogManager.w("xiaoyuan", "DBManager getSQLiteDatabase error: ", e);
                /*SDK-550 hewengao 20160719 end*/
            }
        }
        return sb;
    }

    private synchronized static MyDbHelper getHelper(Context contexts) {

        if (dbHelper == null) {
            dbHelper = new MyDbHelper(contexts, dataBaseName, null,
                    dataBaseVersion);
        }
        return dbHelper;
    }

    private static class MyDbHelper extends SQLiteOpenHelper {
        public MyDbHelper(Context contexts, String name, CursorFactory factory,
                int version) {
            super(contexts, name, factory, version);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {

            try {
                createDb(db);
            } catch (Throwable e) {
                // e.printStackTrace();
                /*SDK-550 hewengao 20160719 start*/
                LogManager.e("xiaoyuan","MyDbHelper onCreate error: ", e);
                /*SDK-550 hewengao 20160719 end*/
            }
        }

        @Override
        public void onOpen(SQLiteDatabase db) {
            try {
                super.onOpen(db);
            } catch (Throwable e) {
                /*SDK-550 hewengao 20160719 start*/
                LogManager.e("xiaoyuan","MyDbHelper onOpen error: ", e);
                /*SDK-550 hewengao 20160719 end*/
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            createDb(db);
        }

        @Override
        public void onDowngrade(SQLiteDatabase db, int oldVersion,
                int newVersion) {
            try {
                db.execSQL(SysParamEntityManager.DROP_TABLE);
                db.execSQL(IccidInfoManager.DROP_TABLE);
                db.execSQL(PubInfoManager.DROP_TABLE_PUBLIC_INFO);
                db.execSQL(PubInfoManager.DROP_TABLE_PUBLIC_MENU_INFO);
                db.execSQL(PubInfoManager.DROP_TABLE_PUBLIC_NUM_INFO);
                db.execSQL(CenterNumLocationInfo.DROP_TABLE);
                db.execSQL(SceneconfigManager.DROP_TABLE);
                db.execSQL(ResdownloadManager.DROP_TABLE);
                db.execSQL(SceneRuleManager.DROP_TABLE);
                db.execSQL(JarSubInfoManager.DROP_TABLE);
                db.execSQL(CountSceneManager.DROP_TABLE);
                db.execSQL(PopupActionManager.DROP_TABLE);
                db.execSQL(menuActionManager.DROP_TABLE);
                db.execSQL(RecordActionManager.DROP_TABLE);
                db.execSQL(TrainManager.DROP_TABLE);
                db.execSQL(AirManager.DROP_TABLE);
                db.execSQL(MenuInfoManager.DROP_TABLE);
                db.execSQL(MatchCacheManager.DROP_TABLE);
                db.execSQL(UpdateTaskManager.DROP_TABLE);
                db.execSQL(XmlResdownloadManager.DROP_TABLE);
                db.execSQL(ResourseManager.DROP_TABLE);
                db.execSQL(PhoneSmsParseManager.DROP_TABLE);
                db.execSQL(NetQueryTimeManager.DROP_TABLE);
                db.execSQL(NumNameManager.DROP_TABLE);
                db.execSQL(SmsParseRecorder.DROP_TABLE);
                /* SDK-421 huangzhiqiang 20160525 start */
                db.execSQL(ShardDataManager.DROP_TABLE);
                /* SDK-421 huangzhiqiang 20160525 end */
                /* SDK-681 zhaojiangwei 20161117 start */
                db.execSQL(PhoneNumServeManager.DROP_TABLE);
                /* SDK-681 zhaojiangwei 20161117 end */
                /* RM-1351 huangzhiqiang 20170407 start */
                db.execSQL(CountSignInfoManager.DROP_COUNT_SIGN_INFO_TABLE);
                db.execSQL(CountSignInfoManager.DROP_SIGN_GROUP_TABLE);
                /* RM-1351 huangzhiqiang 20170407 end */
                /* RM-1374 mobaohua 20170314 start */
                db.execSQL(UrlPreviewManager.DROP_TABLE);
                /* RM-1374 mobaohua 20170314 end */
                /* RM-1467 mobaohua 20170406 start */
                db.execSQL(MovieMessageManager.DROP_TABLE);
                /* RM-1467 mobaohua 20170406 end */
            } catch (Throwable e) {
                /*SDK-550 hewengao 20160719 start*/
                LogManager.e("xiaoyaun","DBManager onDowngrade", e);
                /*SDK-550 hewengao 20160719 end*/
                /* SDK-584 zhaojiangwei 20160906 start */
                DexUtil.saveExceptionLog(e);
                /* SDK-584 zhaojiangwei 20160906 end */
            }
            createDb(db);
        }
    }

    public static void createDb(SQLiteDatabase SQLiteDatabase) {
        try {
            SQLiteDatabase.execSQL(SysParamEntityManager.CREATE_TABLE);
            // SQLiteDatabase.execSQL(ParseItemManager.CREATE_TABLE);
            // SQLiteDatabase.execSQL(ParseItemManager.CREATE_INDEX);

            SQLiteDatabase.execSQL(IccidInfoManager.CREATE_TABLE);

            SQLiteDatabase.execSQL(PubInfoManager.getCreatePubInfoTableSql());
            SQLiteDatabase.execSQL(PubInfoManager
                    .getCreatePubmenuInfoTableSql());
            SQLiteDatabase
                    .execSQL(PubInfoManager.getCreatePubNumInfoTableSql());
            SQLiteDatabase.execSQL(CenterNumLocationInfo.CREATE_TABLE);

            SQLiteDatabase.execSQL(SceneconfigManager.CREATE_TABLE);
            SQLiteDatabase.execSQL(ResdownloadManager.CREATE_TABLE);
            SQLiteDatabase.execSQL(SceneRuleManager.CREATE_TABLE);
            SQLiteDatabase.execSQL(JarSubInfoManager.CREATE_TABLE);
            SQLiteDatabase.execSQL(CountSceneManager.CREATE_TABLE);
            SQLiteDatabase.execSQL(PopupActionManager.CREATE_TABLE);
            SQLiteDatabase.execSQL(menuActionManager.CREATE_TABLE);
            SQLiteDatabase.execSQL(RecordActionManager.CREATE_TABLE);


            SQLiteDatabase.execSQL(TrainManager.CREATE_TABLE);
            SQLiteDatabase.execSQL(AirManager.CREATE_TABLE);
            SQLiteDatabase.execSQL(MenuInfoManager.CREATE_TABLE);
            SQLiteDatabase.execSQL(MatchCacheManager.getCreateTableSql());
            SQLiteDatabase.execSQL(UpdateTaskManager.CREATE_TABLE);

            SQLiteDatabase.execSQL(XmlResdownloadManager.CREATE_TABLE);

            SQLiteDatabase.execSQL(ResourseManager.getCreateTableSql());
            SQLiteDatabase.execSQL(PhoneSmsParseManager.getCreateTableSql());
            SQLiteDatabase.execSQL(NetQueryTimeManager.getCreateTableSql());
            SQLiteDatabase.execSQL(NumNameManager.getCreateTableSql());

            SQLiteDatabase.execSQL(EmergencyManger.getCreateTableSql());
            
            SQLiteDatabase.execSQL(OperatorCmdManager.getCreateTableSql());
            SQLiteDatabase.execSQL(OperatorParseManager.getCreateTableSql());
            SQLiteDatabase.execSQL(MsgUrlManager.getCreateTableSql());
            /* SDK-421 huangzhiqiang 20160525 start */
            SQLiteDatabase.execSQL(ShardDataManager.CREATE_TABLE);
            /* SDK-421 huangzhiqiang 20160525 start */
            
            /* hewengao 20161018 start */
            SQLiteDatabase.execSQL(JarSignManager.getCreateTableSql());
            /* hewengao 20161018 end */
            
            /* SDK-681 zhaojiangwei 20161117 start */
            SQLiteDatabase.execSQL(PhoneNumServeManager.CREATE_TABLE);
            /* SDK-681 zhaojiangwei 20161117 end */

            /* RM-1374 mobaohua 20170314 start */
            SQLiteDatabase.execSQL(UrlPreviewManager.CREATE_TABLE);
            /* RM-1374 mobaohua 20170314 end */
            /* RM-1467 mobaohua 20170406 start */
            SQLiteDatabase.execSQL(MovieMessageManager.CREATE_TABLE);
            /* RM-1467 mobaohua 20170406 end */

            /* RM-1351 huangzhiqiang 20170407 start */
            SQLiteDatabase.execSQL(CountSignInfoManager.getCreateCountSignInfoTableSql());
            SQLiteDatabase.execSQL(CountSignInfoManager.getCreateSignGroupTableSql());
            /* RM-1351 huangzhiqiang 20170407 end */

        } catch (Throwable e) {
            // e.printStackTrace();
        }

        try {
            SQLiteDatabase.execSQL(PubInfoManager.ADD_CLASSIFY_CODE);
        } catch (Throwable e) {
            // e.printStackTrace();
        }

        try {
            SQLiteDatabase.execSQL(SceneconfigManager.ADD_IS_CHECK);
        } catch (Throwable e) {
            // e.printStackTrace();
        }

        try {
            SQLiteDatabase.execSQL(SceneconfigManager.ADD_USECOUNT);

        } catch (Throwable e) {
            // e.printStackTrace();
        }
        try {
            SQLiteDatabase.execSQL(SceneconfigManager.ADD_IS_USE);
        } catch (Throwable e) {
            // e.printStackTrace();
        }

        try {
            SQLiteDatabase.execSQL(JarSubInfoManager.ADD_IS_USE);
        } catch (Throwable e) {
            // TODO: handle Throwable
        }

        try {
            SQLiteDatabase.execSQL(TrainManager.ADD_STATION_LIST);
        } catch (Throwable e) {
            // TODO: handle Throwable
        }

        try {
            SQLiteDatabase.execSQL(TrainManager.ADD_DATA_TIME);
        } catch (Throwable e) {
            // TODO: handle Throwable
        }

        try {
            SQLiteDatabase.execSQL(MatchCacheManager.ADD_bubble_lasttime);
        } catch (Throwable e) {
            // TODO: handle Throwable
        }
        try {
            SQLiteDatabase.execSQL(MatchCacheManager.ADD_card_lasttime);
        } catch (Throwable e) {
            // TODO: handle Throwable
        }
        try {
            SQLiteDatabase.execSQL(MatchCacheManager.ADD_session_lasttime);
        } catch (Throwable e) {
            // TODO: handle Throwable
        }
        addColumn(SQLiteDatabase, PubInfoManager.ADD_LOADTIME);
        addColumn(SQLiteDatabase, PubInfoManager.ADD_ISRULENUM);
        addColumn(SQLiteDatabase, NetQueryTimeManager.ADD_AREACODE);

        addColumn(SQLiteDatabase, IccidInfoManager.ADD_USER_PROVINCES);
        addColumn(SQLiteDatabase, IccidInfoManager.ADD_USER_AREACODE);
        addColumn(SQLiteDatabase, IccidInfoManager.ADD_USER_OPERATOR);
        addColumn(SQLiteDatabase, IccidInfoManager.ADD_SIM_INDEX);

        addColumn(SQLiteDatabase, NumNameManager.ADD_CNUM);
        addColumn(SQLiteDatabase, NumNameManager.ADD_MARK_TIME);
        addColumn(SQLiteDatabase, NumNameManager.ADD_CMD);
        addColumn(SQLiteDatabase, PubInfoManager.ADD_CORP_LEVEL);
        
        addColumn(SQLiteDatabase, MatchCacheManager.ADD_urls);
        addColumn(SQLiteDatabase, MatchCacheManager.ADD_url_valid_statu);
        addColumn(SQLiteDatabase, JarSubInfoManager.ADD_PVER);
        
        /* SDK-376 mobaohua 20160331 start */
        addColumn(SQLiteDatabase, RecordActionManager.ADD_ACTION_CODE);
        try {
            SQLiteDatabase.execSQL(RecordActionManager.UPDATE_ACTION_CODE);
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, e.getMessage());
        }
        /* SDK-376 mobaohua 20160331 end */

        //  创建短信识别数据表
        try {
            SQLiteDatabase.execSQL(SmsParseRecorder.CREATE_TABLE);
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, e.getMessage());
        }
        
        addColumn(SQLiteDatabase, PubInfoManager.ADD_IS_USE);

        /*SDK-524 zhaojiangwei 20160708 start */
        addColumn(SQLiteDatabase, PubInfoManager.ADD_COLUMN_RID);
        addColumn(SQLiteDatabase, PubInfoManager.ADD_COLUMN_LOGOTYPE);
        /*SDK-524 zhaojiangwei 20160708 end */

        /* SDK-631 huangzhiqiang 20161008 start */
        addColumn(SQLiteDatabase, PubInfoManager.ADD_COLUMN_SCALE);
        /* SDK-631 huangzhiqiang 20161008 end */
        
        /* SDK-704 zhaojiangwei 20161217 start */
        addColumn(SQLiteDatabase, PubInfoManager.ADD_COLUMN_BACKCOLOR);
        addColumn(SQLiteDatabase, PubInfoManager.ADD_COLUMN_BACKCOLOREND);
        /* SDK-704 zhaojiangwei 20161217 end */
        
        //SDK-383 特征值识别  xusongzhou 20160412 start
        addColumn(SQLiteDatabase, MatchCacheManager.ADD_recognise_result);
        addColumn(SQLiteDatabase, MatchCacheManager.ADD_recognise_lasttime);
        //SDK-383 特征值识别  xusongzhou 20160412 end

        /* SDK-397 huangzhiqiang 20160526 start */
        addColumn(SQLiteDatabase, PubInfoManager.ADD_NAME_TYPE);
        addColumn(SQLiteDatabase, NumNameManager.ADD_MARK_CMD);
        addColumn(SQLiteDatabase, NumNameManager.ADD_LAST_NAME_PUBID);
        addColumn(SQLiteDatabase, NumNameManager.ADD_LAST_NAME_TIME);
        addColumn(SQLiteDatabase, NumNameManager.ADD_LAST_CMD_TIME);
        addColumn(SQLiteDatabase, NumNameManager.ADD_LAST_QUERY_TIME);
        /* SDK-397 huangzhiqiang 20160526 end */
        /* SDK-459/yangzhi/2016.05.26---start--- */
        addColumn(SQLiteDatabase, TrainManager.ADD_DAY);
        /* SDK-459/yangzhi/2016.05.26---end--- */
        /* SDK-465/yangzhi/2016.05.30---start--- */
        SQLiteDatabase.execSQL(TrainManager.DROP_OLD_TABLE);
        /* SDK-465/yangzhi/2016.05.30---end--- */

        /* SDK-500 huangzhiqiang 20160621 start */
        addColumn(SQLiteDatabase, NetQueryTimeManager.ADD_STATUS);
        /* SDK-500 huangzhiqiang 20160621 end */
        /* SDK-478 huangzhiqiang 20160628 start */
        addColumn(SQLiteDatabase, NumNameManager.ADD_EC);
        addColumn(SQLiteDatabase, NumNameManager.ADD_MARK_EC);
        addColumn(SQLiteDatabase, NumNameManager.ADD_LAST_EC_TIME);
        /* SDK-478 huangzhiqiang 20160628 end */

        /* SDK-529 huangzhiqiang 20160711 start */
        addColumn(SQLiteDatabase, OperatorParseManager.CLEAR_MSG_FIELD_DATA);
        addColumn(SQLiteDatabase, OperatorParseManager.ADD_NUM_MSG_MD5);
        /* SDK-529 huangzhiqiang 20160711 end */
        
        /*MEIZU-1142 zhaojiangwei 20160908 start*/
        addColumn(SQLiteDatabase, MatchCacheManager.ADD_URLS_RESULT);
        addColumn(SQLiteDatabase, MatchCacheManager.ADD_URLS_LASTTIME);
        /*MEIZU-1142 zhaojiangwei 20160908 end*/

         /* SDK-632 hewengao 20161010 start*/
         addColumn(SQLiteDatabase,SceneconfigManager.ADD_lAST_UPDATE_TIME);
         addColumn(SQLiteDatabase,SceneRuleManager.ADD_ISUSE);
         addColumn(SQLiteDatabase,SceneRuleManager.ADD_lAST_UPDATE_TIME);
         /* SDK-632 hewengao 20161010 end*/

        /* SDK-654  hewengao 20161026 start*/
        addColumn(SQLiteDatabase,SceneRuleManager.ADD_SCENE_RULE_CONFIG);
        addColumn(SQLiteDatabase,SceneRuleManager.CREATE_SCENE_AND_TYPE_IDX);
        /* SDK-654 hewengao 20161026 end*/
        
        addColumn(SQLiteDatabase, MatchCacheManager.ADD_IS_FAVORITE);
        addColumn(SQLiteDatabase, MatchCacheManager.ADD_IS_MARK);

    }

    private static void addColumn(SQLiteDatabase SQLiteDatabase, String sql) {
        try {
            SQLiteDatabase.execSQL(sql);
        } catch (Throwable e) {
        }
    }

    private static SQLiteDatabase getReadSQLiteDatabase() {
        return getSQLiteDatabase();
    }

    public static XyCursor query(String tableName, String[] columns,
            String selection, String[] selectionArgs) throws Exception {
        return query(false, tableName, columns, selection, selectionArgs, null,
                null, null, null);
    }

    private static boolean dbInTransaction(SQLiteDatabase mySQLiteDatabase) {
        if (mySQLiteDatabase != null && mySQLiteDatabase.inTransaction()) {
            close(mySQLiteDatabase);
            /*SDK-550 hewengao 20160719 start*/
            LogManager.d("xiaoyuan", "DBManager db inTransaction threadName:");
            /*SDK-550 hewengao 20160719 end*/
            return true;
        }
        return false;
    }

    public static XyCursor query(boolean distinct, String tableName,
            String[] columns, String selection, String[] selectionArgs,
            String groupBy, String having, String orderBy, String limit)
            throws Exception {

        XyCursor xyCursor = null;
        SQLiteDatabase mySQLiteDatabase = null;
        try {
            mySQLiteDatabase = getReadSQLiteDatabase();
            if(mySQLiteDatabase == null){
                return null;
            }
            if (dbInTransaction(mySQLiteDatabase)) {
                return null;
            }
            Cursor cursor = mySQLiteDatabase.query(distinct, tableName,
                    columns, selection, selectionArgs, groupBy, having,
                    orderBy, limit);
            /* SDK-531 huangzhiqiang 20160711 start */
            xyCursor = new XyCursor(mySQLiteDatabase, cursor, 0);
            /* SDK-531 huangzhiqiang 20160711 end */
        } catch (Throwable e) {
            close(mySQLiteDatabase);
            /*SDK-550 hewengao 20160719 start*/
            LogManager.e("xiaoyuan","DBManager 1query error: ", e);
            /*SDK-550 hewengao 20160719 end*/
            /* SDK-584 zhaojiangwei 20160906 start */
            DexUtil.saveExceptionLog(e);
            /* SDK-584 zhaojiangwei 20160906 end */
        }
        return xyCursor;
    }

    public static XyCursor query(String tableName, String[] columns,
            String selection, String[] selectionArgs, String groupBy,
            String having, String orderBy, String limit) throws Exception {
        // initDbManager();
        XyCursor xyCursor = null;
        SQLiteDatabase mySQLiteDatabase = null;
        try {
            mySQLiteDatabase = getSQLiteDatabase();
            if (dbInTransaction(mySQLiteDatabase)) {
                return null;
            }
            Cursor cursor = mySQLiteDatabase.query(tableName, columns,
                    selection, selectionArgs, groupBy, having, orderBy, limit);
            /* SDK-531 huangzhiqiang 20160711 start */
            xyCursor = new XyCursor(mySQLiteDatabase, cursor, 0);
            /* SDK-531 huangzhiqiang 20160711 end */
        } catch (Throwable e) {
            close(mySQLiteDatabase);
            /*SDK-550 hewengao 20160719 start*/
            LogManager.e("xiaoyuan","DBManager 2query error: ", e);
            /*SDK-550 hewengao 20160719 end*/
            /* SDK-584 zhaojiangwei 20160906 start */
            DexUtil.saveExceptionLog(e);
            /* SDK-584 zhaojiangwei 20160906 end */
        } finally {

        }
        return xyCursor;
    }

    // public static XyCursor queryPatternString( SQLiteDatabase
    // mySQLiteDatabase,boolean distinct, String tableName, String[] columns,
    // String selection, String[] selectionArgs, String groupBy, String having,
    // String orderBy, String limit,Context context)
    // throws Throwable {
    // // initDbManager();
    // XyCursor xyCursor = null;
    // try {
    //
    // Cursor cursor = mySQLiteDatabase.query(distinct, tableName, columns,
    // selection, selectionArgs, groupBy, having, orderBy, limit);
    // xyCursor = new XyCursor(null, cursor);
    // } catch (Throwable e) {
    // e.printStackTrace();
    // }
    // return xyCursor;
    // }
    // cccccccccc
    public static int delete(String tableName, String whereClause,
            String[] whereArgs) throws Exception {
        // initDbManager();

        synchronized (dblock) {
            int res = -1;
            SQLiteDatabase mySQLiteDatabase = null;
            try {
                mySQLiteDatabase = getSQLiteDatabase();
                res = mySQLiteDatabase
                        .delete(tableName, whereClause, whereArgs);
                // LogManager.i("delete res:"+res);
            } catch (Throwable e) {
                res = -1;
            } finally {
                close(mySQLiteDatabase);
            }
            return res;
        }
    }

    /*
     * public static int specialUpdate(String tableName, ContentValues values,
     * String whereClause, String[] whereArgs, SQLiteDatabase
     * mySQLiteDatabase)throws Throwable { synchronized (dblock) { int res = -1;
     * try { res = mySQLiteDatabase.update(tableName, values, whereClause,
     * whereArgs); } catch (Throwable e) { res = -1; throw e; } return res; } }
     * 
     * public static long specialInsert(String tableName, ContentValues values,
     * SQLiteDatabase mySQLiteDatabase) throws Throwable { synchronized (dblock)
     * { long res = -1; try { res=mySQLiteDatabase.insert(tableName,
     * null,values); } catch (Throwable e) { res = -1; throw e; } return res; }
     * }
     */

    public static int update(String tableName, ContentValues values,
            String whereClause, String[] whereArgs) throws Exception {
        synchronized (dblock) {
            int res = -1;
            SQLiteDatabase mySQLiteDatabase = null;
            try {
                mySQLiteDatabase = getSQLiteDatabase();
                res = mySQLiteDatabase.update(tableName, values, whereClause,
                        whereArgs);
            } catch (Throwable e) {
                res = -1;
            } finally {
                close(mySQLiteDatabase);
            }
            return res;
        }
    }

    public static long insert(String tableName, ContentValues values)
            throws Exception {
        synchronized (dblock) {
            long res = -1;
            SQLiteDatabase mySQLiteDatabase = null;
            try {
                mySQLiteDatabase = getSQLiteDatabase();
                res = mySQLiteDatabase.insert(tableName, null, values);
            } catch (Throwable e) {
                res = -1;
            } finally {
                close(mySQLiteDatabase);
            }
            return res;
        }
    }

    public static XyCursor rawQuery(String sql, String[] selectionArgs)
            throws Exception {
        // initDbManager();
        SQLiteDatabase mySQLiteDatabase = null;
        XyCursor xyCursor = null;

        try {
            mySQLiteDatabase = getSQLiteDatabase();
            if (dbInTransaction(mySQLiteDatabase)) {
                return null;
            }
            Cursor cursor = mySQLiteDatabase.rawQuery(sql, selectionArgs);
            /* SDK-531 huangzhiqiang 20160711 start */
            xyCursor = new XyCursor(mySQLiteDatabase, cursor, 0);
            /* SDK-531 huangzhiqiang 20160711 end */
        } catch (Throwable e) {
            close(mySQLiteDatabase);
            /*SDK-550 hewengao 20160719 start*/
            LogManager.e("xiaoyuan","DBManager rawQuery error: ", e);
            /*SDK-550 hewengao 20160719 end*/
        }
        return xyCursor;
    }

    /* SDK-396 huangzhiqiang 20160418 start */
    public static boolean excSql(String filePath, boolean isDeleteFile)
            throws Throwable {
        if(StringUtils.isNull(filePath)){
            return false;
        }
        return excSql(new File(filePath), isDeleteFile);
    }

    public static boolean excSql(File file, boolean isDeleteFile)
            throws Throwable {
        if(file == null || !file.exists()){
            return false;
        }

        SQLiteDatabase db = null;
        BufferedReader bw = null;
        java.io.LineNumberReader r = null;
        try {
            bw = new BufferedReader(new FileReader(file));
            r = new LineNumberReader(bw);
            String line = null;
            db = DBManager.getSQLiteDatabase();
            db.beginTransaction();

            try {
                while ((line = r.readLine()) != null) {
                    if (!StringUtils.isNull(line)) {
                        db.execSQL(line);// 执行每行的sql
                    }
                }
                r.close();
            } catch (Throwable e) {
                /*SDK-550 hewengao 20160719 start*/
                LogManager.e(Constant.TAG, "excSql: ", e);
                /*SDK-550 hewengao 20160719 end*/
                throw e;
            }
            return true;
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "excSql: ", e);
        } finally {
            closeDB(file, isDeleteFile, r, bw, db);
        }
        return false;
    }

    public static void closeDB(String filePath, boolean isDeleteFile,
            java.io.LineNumberReader r, BufferedReader bw, SQLiteDatabase db) {
        File file = null;
        try {
            if (isDeleteFile) {
                file = new File(filePath);
            }
        } catch (Throwable ex) {
            /*SDK-550 hewengao 20160719 start*/
            LogManager.e("xiaoyuan", "DBManager closeDB error: ", ex);
            /*SDK-550 hewengao 20160719 end*/
        }
        closeDB(file, isDeleteFile, r, bw, db);
    }

    public static void closeDB(File file, boolean isDeleteFile,
            java.io.LineNumberReader r, BufferedReader bw, SQLiteDatabase db) {
        try {
            try {
                if (isDeleteFile) {
                    FileUtils.deleteAllFile(file);
                }
            } catch (Throwable e2) {
                // TODO: handle Throwable
            }

            try {
                if (r != null)
                    r.close();
            } catch (Throwable e2) {
                // TODO: handle Throwable
            }

            try {
                if (bw != null)
                    bw.close();
            } catch (Throwable e2) {
                // TODO: handle Throwable
            }

            if (db != null) {
                try {
                    if (db.inTransaction()) {
                        db.setTransactionSuccessful();
                        db.endTransaction();
                    }
                } catch (Throwable e) {
//                    e.printStackTrace();
                    /*SDK-550 hewengao 20160719 start*/
                    LogManager.e(Constant.TAG, "closeDB: ", e);
                    /*SDK-550 hewengao 20160719 end*/

                } finally {
                    DBManager.close(db);
                }
            }
        } catch (Throwable e) {
            LogManager.e("xiaoyuan","DBManager closeDB error: ", e);
        }
    }
    /* SDK-396 huangzhiqiang 20160418 end */

    public static void closeCursor(Cursor cur) {
        if (cur != null) {
            cur.close();
        }
    }

    public static long saveOrUpdateTableData(String tableName,
            ContentValues values, String whereClause, String whereArgs[]) {
        long flag = 0;
        try {
            flag = DBManager.update(tableName, values, whereClause, whereArgs);
            if (flag < 1) {
                flag = DBManager.insert(tableName, values);
            } else {
                flag = -flag;
            }
        } catch (Throwable e) {
            // TODO Auto-generated catch block
            // e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.e("xiaoyuan", "DBManager saveOrUpdateTableData error: ", e);
            /*SDK-550 hewengao 20160719 end*/
        }
        return flag;
    }

    /* SDK-554 huangzhiqiang 20160721 start */
    public static void execSQL(final String sql) {
        if (StringUtils.isNull(sql)) {
            return;
        }
        try {
            SQLiteDatabase db = null;
            try {
                db = DBManager.getSQLiteDatabase();
                db.execSQL(sql);
            } catch (Throwable e) {
                LogManager.e(Constant.TAG, "execSQL: ", e);
            } finally {
                DBManager.close(db);
            }
        } catch (Throwable e) {
            /*SDK-550 hewengao 20160719 start*/
            LogManager.e(Constant.TAG, "execSQL: ", e);
            /*SDK-550 hewengao 20160719 end*/
        }
    }
    /* SDK-554 huangzhiqiang 20160721 end */
}
